"""数据处理层"""

import json
import os

from conf import settings


def save(userdata):
    """用户数据字典对象序列化保存到本地"""
    if not os.path.exists(settings.USERDATA_PATH):
        os.mkdir(settings.USERDATA_PATH)
    username = userdata.get('username')
    fp = os.path.join(settings.USERDATA_PATH, f'{username}.json')
    with open(fp, 'wt', encoding='utf-8') as f:
        json.dump(userdata, f)


def select(username):
    """返回None或者用户数据（字典）"""
    fp = os.path.join(settings.USERDATA_PATH, f'{username}.json')
    if not os.path.exists(fp):
        return None
    with open(fp, 'rt', encoding='utf-8') as f:
        userdata = json.load(f)
        return userdata
